#include "ruleeditordialog.h"
#include "ui_ruleeditordialog.h"
#include <QMessageBox>

RuleEditorDialog::RuleEditorDialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::RuleEditorDialog)
{
    ui->setupUi(this);

    // 设备ID从数据库加载
    ui->comboDeviceId->addItems({"1", "2", "3"});

    connect(ui->btnOk, &QPushButton::clicked, this, &RuleEditorDialog::onOkClicked);
    connect(ui->btnCancel, &QPushButton::clicked, this, &RuleEditorDialog::onCancelClicked);
}

RuleEditorDialog::~RuleEditorDialog()
{
    delete ui;
}

void RuleEditorDialog::setEditData(const QVariantMap &data)
{
    ui->comboDeviceId->setCurrentText(data.value("device_id").toString());
    ui->editDescription->setText(data.value("description").toString());

    QString condition = data.value("condition").toString();
    QStringList parts = condition.split(" ");
    ui->comboField->setCurrentText(parts.value(0));
    ui->comboOperator->setCurrentText(parts.value(1));
    ui->editValue->setText(parts.value(2));

    ui->comboAction->setCurrentText(data.value("action").toString());
    ui->comboSeverity->setCurrentText(data.value("severity").toString());
    ui->checkEnabled->setChecked(data.value("is_enabled").toInt() == 1);
}

QVariantMap RuleEditorDialog::getRuleData() const
{
    QVariantMap data;
    data["device_id"] = ui->comboDeviceId->currentText();
    data["description"] = ui->editDescription->text();
    data["condition"] = QString("%1 %2 %3")
                            .arg(ui->comboField->currentText())
                            .arg(ui->comboOperator->currentText())
                            .arg(ui->editValue->text());
    data["action"] = ui->comboAction->currentText();
    data["severity"] = ui->comboSeverity->currentText();
    data["is_enabled"] = ui->checkEnabled->isChecked() ? 1 : 0;
    return data;
}

void RuleEditorDialog::onOkClicked()
{
    if (ui->editDescription->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "规则描述不能为空！");
        return;
    }
    if (ui->editValue->text().isEmpty()) {
        QMessageBox::warning(this, "警告", "触发值不能为空！");
        return;
    }
    accept();
}

void RuleEditorDialog::onCancelClicked()
{
    reject();
}
